package middleware

import (
	"github.com/gin-gonic/gin"
	"net/url"
	"root/config"
	"root/controller"
	"sort"
	"strings"
	"root/utility"
	//"root/config"
)

func Sign () gin.HandlerFunc  {
	return func(c *gin.Context) {
		sign   := c.PostForm("sign")
		token  := c.PostForm("token")
		post   := c.Request.PostForm

		if sign == "" {
			controller.SendResponse(c,1003,"",nil)
			c.Abort()
			return
		}

		res := CheckSign(PostFormToSortGetParam(post) ,sign,token)

		if !res {
			controller.SendResponse(c,1000,"",nil)
			c.Abort()
			return
		}

	}
}
/**
   post表单map数据转排序后的get参数
 */
func PostFormToSortGetParam(post map[string][]string) string {
	paramMap := map[string]string{}
	keys := []string{}
	var getParam = ""
	for field,val := range post {

		if(field != "token" && field != "sign"){
			paramMap[field] = strings.Join(val, "")
			keys = append(keys, field)
		}
	}
	sort.Strings(keys)
	for _,field := range keys {
		getParam += field +"="+ paramMap[field] +"&"
	}
	getParam = getParam[0 : len(getParam)-1]
	return getParam
}

func CheckSign(getParam string ,sign string,token string) bool {

	conf ,err := config.GetConfig("auth")
	if(err != nil){
		return false
	}
	salt := conf["slat"].(string)
	getParam ,err = url.QueryUnescape(getParam)
	if(err != nil){
		return false
	}
	getParam ,err = url.QueryUnescape(getParam)
	if(err != nil){
		return false
	}
	var serSign = strings.ToUpper(utility.Md5(utility.Md5(getParam + salt + token)))
	if serSign !=  sign{
		return false
	}

	return true
}